package com.nuoniu.sibanyun.config;

import com.nuoniu.sibanyun.entity.SysUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class JwtUser implements UserDetails {

    private Long id;
    private String username;
    private String password;
    private Collection<? extends GrantedAuthority> authorities;

    public JwtUser() {
    }

    public JwtUser(SysUser user) {
        id = user.getId();
        username = user.getUserName();
        password = user.getPassword();
    }

    // 写一个能直接使用user创建jwtUser的构造器
    public JwtUser(SysUser user, String p) {
        id = user.getId();
        username = user.getUserName();
        password = user.getPassword();
        this.setAuthorities(p);
//        authorities = Collections.singleton(new SimpleGrantedAuthority());
    }
    public JwtUser(SysUser user, Collection<? extends GrantedAuthority> authorities) {
        id = user.getId();
        username = user.getUserName();
        password = user.getPassword();
        this.authorities =authorities;
    }
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }
    @Override
    public String getPassword() {
        return password;
    }
    @Override
    public String getUsername() {
        return username;
    }
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
    @Override
    public boolean isEnabled() {
        return true;
    }

    public void setAuthorities(String permisons){
        Collection<GrantedAuthority> a = new ArrayList<>();
        String[] arr = permisons.split(",");
        for (String p : arr) {
            a.add(new SimpleGrantedAuthority(p));
        }

        this.authorities = a;

    }
    public Long getId() {
        return id;
    }
    @Override
    public String toString() {
        return "JwtUser{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", authorities=" + authorities +
                '}';
    }

}
